package com.springboot.others.handler;

import com.springboot.others.common.Result;
import com.springboot.others.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 专门捕获数据库异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
//    Duplicate entry '111445' for key 'employee.idx_username'
//        判断是否是键值对重复异常
        if (ex.getMessage().contains("Duplicate entry")){
//            根据已有的报错信息，分割这类的报错信息提取出重复的键：username
            String[] message = ex.getMessage().split(" ");
            String username = message[2];

            String msg = username + ":已存在";
            return Result.error(msg);
        }else if (ex.getMessage().contains("a foreign key constraint fails")){
            return Result.error(ex.getMessage() + ":因当前字段含外键约束，无法操作");
        }
        else {
            return Result.error(ex.getMessage() + ":未知错误");
        }
    }

}